<template>
  <div>
    <!-- 搜索框 -->
    <form action="/">
      <van-search
        v-model.trim="keywords"
        show-action
        background="#3796eb"
        class="search-ipt"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isShowResult = false"
      />
    </form>
    <!-- 搜索结果/建议/历史 -->
    <component
      :keywords="keywords"
      :is="componentName"
      @updateKeywords="onSearch"
    ></component>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import SearchHistory from './components/SearchHistory.vue'
import SearchResult from './components/SearchResult.vue'
import SearchSuggestions from './components/SearchSuggestions.vue'
export default {
  components: { SearchResult, SearchSuggestions, SearchHistory },
  data() {
    return { keywords: '', isShowResult: false }
  },
  methods: {
    ...mapMutations(['SET_HISTORIES']),
    onSearch(val) {
      this.keywords = val
      this.SET_HISTORIES([...new Set([this.keywords, ...this.histories])])
      this.isShowResult = true
    },
    onCancel() {
      // console.log('取消')
      if (this.keywords === '') {
        this.$router.go(-1)
      }
      // else {
      //   // console.log(1);
      //   this.keywords = ''
      //   this.$router.go(1)
      // }
    }
  },
  computed: {
    ...mapState(['histories']),
    componentName() {
      if (this.keywords === '') {
        return 'SearchHistory'
      }
      if (this.isShowResult) {
        //
        return 'SearchResult'
      }
      return 'SearchSuggestions'
    }
  }
}
</script>

<style scoped lang="less">
.search-ipt {
  .van-search__action {
    color: #fff;
  }
}
</style>